package com.emuporium.gymrat.server.log;

import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.LogDB;
import com.emuporium.gymrat.server.data.LogEntry;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

@SuppressWarnings("serial")
public class LogViewFilterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		boolean useDate = false;
		boolean useRoutine = false;
		boolean useExercise = false;

		Date startDate = null;
		Date endDate = null;

		int routineId = -1;
		int exerciseId = -1;

		User user = UserDB.selectUser(request.getRemoteUser());

		String[] filters = request.getParameterValues("filter");
		if (filters != null) {
			for (String s : filters) {
				if (s.equals("byDate"))
					useDate = true;
				if (s.equals("byRoutine"))
					useRoutine = true;
				if (s.equals("byExercise"))
					useExercise = true;
			}
		}

		if (useDate) {
			String startDateParam = request.getParameter("startDate");
			String endDateParam = request.getParameter("endDate");
			SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

			try {
				startDate = new Date(dateFormat.parse(startDateParam).getTime());
			} catch (Exception e1) {
				startDate = null;
			}

			try {
				endDate = new Date(dateFormat.parse(endDateParam).getTime());
			} catch (Exception e1) {
				endDate = null;
			}

			request.setAttribute("startDate", startDateParam);
			request.setAttribute("endDate", endDateParam);
			request.setAttribute("dateFilter", true);
		}

		if (useRoutine) {
			try {
				routineId = new Integer(request.getParameter("routineSelect"));
			} catch (NumberFormatException e) {
				routineId = -1;
			}
			request.setAttribute("routineFilter", true);
			request.setAttribute("routineChoice", routineId);
		}

		if (useExercise) {
			exerciseId = new Integer(request.getParameter("exerciseSelect"));
			request.setAttribute("exerciseFilter", true);
			request.setAttribute("exerciseChoice", exerciseId);
		}

		ArrayList<LogEntry> log = new ArrayList<LogEntry>();
		log = LogDB.selectLogEntries(user.getId(), startDate, endDate,
				routineId, exerciseId);

		request.setAttribute("log", log);

		String url = "/log/view";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

}
